package GUI;

import util.User;
import util.TravelRecord;
import util.TravelRecordDAO;
import util.DatabaseUtil;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.sql.*;
import javax.swing.SpinnerDateModel;

/**
 * 出行记录面板，用于记录和查询用户的绿色出行记录
 */
public class TravelRecordPanel extends JPanel {
    private User currentUser;
    private JTable recordsTable;
    private DefaultTableModel tableModel;
    private JTextField startLocationField;
    private JTextField endLocationField;
    private JTextField distanceField;
    private JComboBox<String> travelTypeComboBox;
    private JSpinner dateSpinner;
    private JButton addRecordButton;
    private JLabel messageLabel;
    private JLabel pointsPreviewLabel;
    private JLabel carbonPreviewLabel;
    private JPopupMenu locationSuggestionPopup;
    private JList<String> suggestionList;
    private JTextField activeLocationField;
    private List<String> locationHistory = new ArrayList<>();
    private JComboBox<String> filterTypeComboBox;
    private JTextField searchField;
    private TableRowSorter<DefaultTableModel> sorter;

    public TravelRecordPanel(User user) {
        this.currentUser = user;

        // 设置布局
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建标题面板
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setOpaque(false);

        // 创建搜索面板
        JPanel searchPanel = new JPanel();
        searchPanel.setLayout(new BoxLayout(searchPanel, BoxLayout.X_AXIS));
        searchPanel.setOpaque(false);

        // 筛选标签
        JLabel filterLabel = new JLabel("筛选: ");
        filterLabel.setFont(new Font("等线", Font.BOLD, 14));
        filterLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
        searchPanel.add(filterLabel);

        // 出行方式筛选
        filterTypeComboBox = new JComboBox<>(new String[] { "全部", "公交", "地铁", "共享单车", "自行车", "步行", "电动车" });
        filterTypeComboBox.setFont(new Font("等线", Font.PLAIN, 14));
        filterTypeComboBox.setPreferredSize(new Dimension(120, 30));
        filterTypeComboBox.setBackground(Color.WHITE);
        filterTypeComboBox.setFocusable(false);
        filterTypeComboBox.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200), 1),
                BorderFactory.createEmptyBorder(4, 8, 4, 8)));
        filterTypeComboBox.addActionListener(e -> applyFilter());
        searchPanel.add(filterTypeComboBox);

        // 添加距离筛选
        searchPanel.add(Box.createHorizontalStrut(10));
        JLabel distanceLabel = new JLabel("距离: ");
        distanceLabel.setFont(new Font("等线", Font.BOLD, 14));
        distanceLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
        searchPanel.add(distanceLabel);

        JComboBox<String> distanceFilterComboBox = new JComboBox<>(
                new String[] { "全部", "1km以下", "1-3km", "3-5km", "5km以上" });
        distanceFilterComboBox.setFont(new Font("等线", Font.PLAIN, 14));
        distanceFilterComboBox.setPreferredSize(new Dimension(120, 30));
        distanceFilterComboBox.setBackground(Color.WHITE);
        distanceFilterComboBox.setFocusable(false);
        distanceFilterComboBox.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200), 1),
                BorderFactory.createEmptyBorder(4, 8, 4, 8)));
        distanceFilterComboBox.addActionListener(e -> applyFilterDistance(distanceFilterComboBox));
        searchPanel.add(distanceFilterComboBox);

        // 添加日期筛选
        searchPanel.add(Box.createHorizontalStrut(10));
        JLabel dateLabel = new JLabel("日期: ");
        dateLabel.setFont(new Font("等线", Font.BOLD, 14));
        dateLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
        searchPanel.add(dateLabel);

        JComboBox<String> dateFilterComboBox = new JComboBox<>(
                new String[] { "全部", "今天", "本周", "本月", "今年" });
        dateFilterComboBox.setFont(new Font("等线", Font.PLAIN, 14));
        dateFilterComboBox.setPreferredSize(new Dimension(120, 30));
        dateFilterComboBox.setBackground(Color.WHITE);
        dateFilterComboBox.setFocusable(false);
        dateFilterComboBox.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200), 1),
                BorderFactory.createEmptyBorder(4, 8, 4, 8)));
        dateFilterComboBox.addActionListener(e -> applyFilterDate(dateFilterComboBox));
        searchPanel.add(dateFilterComboBox);

        // 搜索框和按钮面板
        searchPanel.add(Box.createHorizontalStrut(15));

        JPanel searchBoxPanel = new JPanel(new BorderLayout(5, 0));
        searchBoxPanel.setOpaque(false);

        // 美化搜索框
        searchField = new JTextField(15);
        searchField.setFont(new Font("等线", Font.PLAIN, 14));
        searchField.putClientProperty("JTextField.placeholderText", "搜索起点或终点...");
        searchField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200), 1),
                BorderFactory.createEmptyBorder(6, 10, 6, 10)));
        searchField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                applyFilter();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                applyFilter();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                applyFilter();
            }
        });
        searchField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    applyFilter();
                }
            }
        });
        searchBoxPanel.add(searchField, BorderLayout.CENTER);

        // 添加搜索按钮
        JButton searchButton = new JButton("搜索");
        searchButton.setFont(new Font("等线", Font.PLAIN, 14));
        searchButton.setBackground(new Color(240, 240, 240));
        searchButton.setForeground(new Color(80, 80, 80));
        searchButton.setFocusPainted(false);
        searchButton.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200), 1),
                BorderFactory.createEmptyBorder(4, 10, 4, 10)));
        searchButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        searchButton.addActionListener(e -> applyFilter());
        searchBoxPanel.add(searchButton, BorderLayout.EAST);

        searchPanel.add(searchBoxPanel);

        titlePanel.add(searchPanel, BorderLayout.EAST);
        add(titlePanel, BorderLayout.NORTH);

        // 创建记录表格面板
        JPanel tablePanel = createTablePanel();
        add(tablePanel, BorderLayout.CENTER);

        // 初始化位置建议弹出菜单
        initLocationSuggestion();

        // 加载位置历史记录
        loadLocationHistory();

        // 加载用户的出行记录
        loadTravelRecords();
    }

    /**
     * 创建记录表格面板
     */
    private JPanel createTablePanel() {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)));

        // 创建表格模型
        tableModel = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 使表格不可编辑
            }

            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if (columnIndex == 4 || columnIndex == 5 || columnIndex == 6) {
                    return Double.class; // 设置数字列的类型为Double以便排序
                }
                return Object.class;
            }
        };

        // 添加列
        tableModel.addColumn("日期");
        tableModel.addColumn("出行方式");
        tableModel.addColumn("起点");
        tableModel.addColumn("终点");
        tableModel.addColumn("距离(km)");
        tableModel.addColumn("获得积分");
        tableModel.addColumn("减碳量(kg)");

        // 创建表格和排序器
        recordsTable = new JTable(tableModel);
        sorter = new TableRowSorter<>(tableModel);
        recordsTable.setRowSorter(sorter);

        // 设置表格样式
        recordsTable.getTableHeader().setReorderingAllowed(false);
        recordsTable.getTableHeader().setFont(new Font("等线", Font.BOLD, 14));
        recordsTable.getTableHeader().setBackground(new Color(245, 250, 245));
        recordsTable.getTableHeader().setForeground(new Color(60, 60, 60));
        recordsTable.getTableHeader().setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, new Color(220, 240, 220)));
        recordsTable.setFont(new Font("等线", Font.PLAIN, 14));
        recordsTable.setRowHeight(30);
        recordsTable.setGridColor(new Color(235, 235, 235));
        recordsTable.setShowVerticalLines(true);
        recordsTable.setShowHorizontalLines(true);
        recordsTable.setSelectionBackground(new Color(220, 240, 220));
        recordsTable.setSelectionForeground(new Color(50, 50, 50));
        recordsTable.setFillsViewportHeight(true);
        recordsTable.setIntercellSpacing(new Dimension(5, 5));
        recordsTable.setAutoCreateRowSorter(true);

        // 创建滚动面板并添加表格
        JScrollPane scrollPane = new JScrollPane(recordsTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.getViewport().setBackground(Color.WHITE);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 创建统计面板
        JPanel statsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 5));
        statsPanel.setOpaque(false);
        statsPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));

        // 美化统计标签
        JLabel totalLabel = new JLabel("总记录: 0");
        totalLabel.setFont(new Font("等线", Font.BOLD, 14));
        totalLabel.setForeground(new Color(80, 80, 80));

        JLabel totalDistanceLabel = new JLabel("总里程: 0.0 km");
        totalDistanceLabel.setFont(new Font("等线", Font.BOLD, 14));
        totalDistanceLabel.setForeground(new Color(80, 80, 80));

        JLabel totalPointsLabel = new JLabel("总积分: 0");
        totalPointsLabel.setFont(new Font("等线", Font.BOLD, 14));
        totalPointsLabel.setForeground(new Color(80, 80, 80));

        JLabel totalCarbonLabel = new JLabel("总碳减排: 0.0 kg");
        totalCarbonLabel.setFont(new Font("等线", Font.BOLD, 14));
        totalCarbonLabel.setForeground(new Color(80, 80, 80));

        statsPanel.add(totalLabel);
        statsPanel.add(totalDistanceLabel);
        statsPanel.add(totalPointsLabel);
        statsPanel.add(totalCarbonLabel);

        // 美化刷新按钮
        JButton refreshButton = new JButton("刷新记录");
        refreshButton.setFont(new Font("等线", Font.BOLD, 14));
        refreshButton.setBackground(new Color(0, 120, 0));
        refreshButton.setForeground(Color.WHITE);
        refreshButton.setFocusPainted(false);
        refreshButton.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(0, 100, 0), 1),
                BorderFactory.createEmptyBorder(8, 15, 8, 15)));
        refreshButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        refreshButton.addActionListener(e -> {
            loadTravelRecords();
            updateStats(totalLabel, totalDistanceLabel, totalPointsLabel, totalCarbonLabel);
        });

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setOpaque(false);
        buttonPanel.add(refreshButton);

        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.setOpaque(false);
        bottomPanel.add(statsPanel, BorderLayout.WEST);
        bottomPanel.add(buttonPanel, BorderLayout.EAST);

        panel.add(bottomPanel, BorderLayout.SOUTH);

        // 更新统计数据
        loadTravelRecords();
        updateStats(totalLabel, totalDistanceLabel, totalPointsLabel, totalCarbonLabel);

        return panel;
    }

    /**
     * 更新统计数据
     */
    private void updateStats(JLabel totalLabel, JLabel totalDistanceLabel, JLabel totalPointsLabel,
            JLabel totalCarbonLabel) {
        int rowCount = tableModel.getRowCount();
        double totalDistance = 0;
        int totalPoints = 0;
        double totalCarbon = 0;

        for (int i = 0; i < rowCount; i++) {
            totalDistance += (Double) tableModel.getValueAt(i, 4);
            totalPoints += (Double) tableModel.getValueAt(i, 5);
            totalCarbon += (Double) tableModel.getValueAt(i, 6);
        }

        totalLabel.setText("总记录: " + rowCount);
        totalDistanceLabel.setText("总里程: " + String.format("%.1f", totalDistance) + " km");
        totalPointsLabel.setText("总积分: " + totalPoints);
        totalCarbonLabel.setText("总碳减排: " + String.format("%.2f", totalCarbon) + " kg");
    }

    /**
     * 应用表格筛选
     */
    private void applyFilter() {
        RowFilter<DefaultTableModel, Object> typeFilter = null;
        String selectedType = (String) filterTypeComboBox.getSelectedItem();

        if (!"全部".equals(selectedType)) {
            typeFilter = RowFilter.regexFilter("^" + selectedType + "$", 1); // 第2列是出行方式
        }

        RowFilter<DefaultTableModel, Object> searchFilter = null;
        String searchText = searchField.getText().trim();
        if (!searchText.isEmpty()) {
            searchFilter = RowFilter.regexFilter("(?i)" + searchText, 2, 3); // 第3、4列是起点终点
        }

        if (typeFilter != null && searchFilter != null) {
            List<RowFilter<DefaultTableModel, Object>> filters = new ArrayList<>();
            filters.add(typeFilter);
            filters.add(searchFilter);
            sorter.setRowFilter(RowFilter.andFilter(filters));
        } else if (typeFilter != null) {
            sorter.setRowFilter(typeFilter);
        } else if (searchFilter != null) {
            sorter.setRowFilter(searchFilter);
        } else {
            sorter.setRowFilter(null);
        }
    }

    /**
     * 应用距离筛选
     */
    private void applyFilterDistance(JComboBox<String> distanceComboBox) {
        String selectedDistance = (String) distanceComboBox.getSelectedItem();
        RowFilter<Object, Object> distanceFilter = null;

        if (!"全部".equals(selectedDistance)) {
            if ("1km以下".equals(selectedDistance)) {
                distanceFilter = new RowFilter<Object, Object>() {
                    @Override
                    public boolean include(Entry<? extends Object, ? extends Object> entry) {
                        Double distance = (Double) ((DefaultTableModel) entry.getModel())
                                .getValueAt((int) entry.getIdentifier(), 4);
                        return distance < 1.0;
                    }
                };
            } else if ("1-3km".equals(selectedDistance)) {
                distanceFilter = new RowFilter<Object, Object>() {
                    @Override
                    public boolean include(Entry<? extends Object, ? extends Object> entry) {
                        Double distance = (Double) ((DefaultTableModel) entry.getModel())
                                .getValueAt((int) entry.getIdentifier(), 4);
                        return distance >= 1.0 && distance < 3.0;
                    }
                };
            } else if ("3-5km".equals(selectedDistance)) {
                distanceFilter = new RowFilter<Object, Object>() {
                    @Override
                    public boolean include(Entry<? extends Object, ? extends Object> entry) {
                        Double distance = (Double) ((DefaultTableModel) entry.getModel())
                                .getValueAt((int) entry.getIdentifier(), 4);
                        return distance >= 3.0 && distance < 5.0;
                    }
                };
            } else if ("5km以上".equals(selectedDistance)) {
                distanceFilter = new RowFilter<Object, Object>() {
                    @Override
                    public boolean include(Entry<? extends Object, ? extends Object> entry) {
                        Double distance = (Double) ((DefaultTableModel) entry.getModel())
                                .getValueAt((int) entry.getIdentifier(), 4);
                        return distance >= 5.0;
                    }
                };
            }
        }

        // 组合筛选条件
        List<RowFilter<? super DefaultTableModel, ? super Integer>> filters = new ArrayList<>();

        // 添加已存在的过滤器
        RowFilter<? super DefaultTableModel, ? super Integer> existingFilter = sorter.getRowFilter();
        if (existingFilter != null) {
            filters.add(existingFilter);
        }

        // 添加距离过滤器
        if (distanceFilter != null) {
            filters.add(distanceFilter);
            sorter.setRowFilter(RowFilter.andFilter(filters));
        } else if (!filters.isEmpty()) {
            sorter.setRowFilter(RowFilter.andFilter(filters));
        } else {
            sorter.setRowFilter(null);
        }
    }

    /**
     * 应用日期筛选
     */
    private void applyFilterDate(JComboBox<String> dateComboBox) {
        String selectedDate = (String) dateComboBox.getSelectedItem();
        RowFilter<Object, Object> dateFilter = null;

        if (!"全部".equals(selectedDate)) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            final String today = sdf.format(calendar.getTime());

            if ("今天".equals(selectedDate)) {
                dateFilter = new RowFilter<Object, Object>() {
                    @Override
                    public boolean include(Entry<? extends Object, ? extends Object> entry) {
                        String date = (String) ((DefaultTableModel) entry.getModel())
                                .getValueAt((int) entry.getIdentifier(), 0);
                        return date.startsWith(today);
                    }
                };
            } else if ("本周".equals(selectedDate)) {
                calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
                final String weekStart = sdf.format(calendar.getTime());
                calendar.add(Calendar.DAY_OF_WEEK, 6);
                final String weekEnd = sdf.format(calendar.getTime());

                dateFilter = new RowFilter<Object, Object>() {
                    @Override
                    public boolean include(Entry<? extends Object, ? extends Object> entry) {
                        String date = (String) ((DefaultTableModel) entry.getModel())
                                .getValueAt((int) entry.getIdentifier(), 0);
                        return date.compareTo(weekStart) >= 0 && date.compareTo(weekEnd) <= 0;
                    }
                };
            } else if ("本月".equals(selectedDate)) {
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                final String monthStart = sdf.format(calendar.getTime());
                calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                final String monthEnd = sdf.format(calendar.getTime());

                dateFilter = new RowFilter<Object, Object>() {
                    @Override
                    public boolean include(Entry<? extends Object, ? extends Object> entry) {
                        String date = (String) ((DefaultTableModel) entry.getModel())
                                .getValueAt((int) entry.getIdentifier(), 0);
                        return date.compareTo(monthStart) >= 0 && date.compareTo(monthEnd) <= 0;
                    }
                };
            } else if ("今年".equals(selectedDate)) {
                final String yearStart = calendar.get(Calendar.YEAR) + "-01-01";
                final String yearEnd = calendar.get(Calendar.YEAR) + "-12-31";

                dateFilter = new RowFilter<Object, Object>() {
                    @Override
                    public boolean include(Entry<? extends Object, ? extends Object> entry) {
                        String date = (String) ((DefaultTableModel) entry.getModel())
                                .getValueAt((int) entry.getIdentifier(), 0);
                        return date.compareTo(yearStart) >= 0 && date.compareTo(yearEnd) <= 0;
                    }
                };
            }
        }

        // 组合筛选条件
        List<RowFilter<? super DefaultTableModel, ? super Integer>> filters = new ArrayList<>();

        // 添加已存在的过滤器
        RowFilter<? super DefaultTableModel, ? super Integer> existingFilter = sorter.getRowFilter();
        if (existingFilter != null) {
            filters.add(existingFilter);
        }

        // 添加日期过滤器
        if (dateFilter != null) {
            filters.add(dateFilter);
            sorter.setRowFilter(RowFilter.andFilter(filters));
        } else if (!filters.isEmpty()) {
            sorter.setRowFilter(RowFilter.andFilter(filters));
        } else {
            sorter.setRowFilter(null);
        }
    }

    /**
     * 初始化位置建议功能
     */
    private void initLocationSuggestion() {
        locationSuggestionPopup = new JPopupMenu();
        suggestionList = new JList<>();
        suggestionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        suggestionList.setFont(new Font("等线", Font.PLAIN, 14));

        JScrollPane scrollPane = new JScrollPane(suggestionList);
        scrollPane.setPreferredSize(new Dimension(200, 150));
        locationSuggestionPopup.add(scrollPane);

        suggestionList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting() && suggestionList.getSelectedValue() != null) {
                String selectedValue = suggestionList.getSelectedValue();
                if (activeLocationField != null) {
                    activeLocationField.setText(selectedValue);
                    locationSuggestionPopup.setVisible(false);
                }
            }
        });
    }

    /**
     * 显示位置建议
     */
    private void showLocationSuggestions(JTextField field) {
        activeLocationField = field;
        String text = field.getText().trim().toLowerCase();

        if (text.isEmpty()) {
            locationSuggestionPopup.setVisible(false);
            return;
        }

        // 过滤位置历史记录
        List<String> filtered = new ArrayList<>();
        for (String location : locationHistory) {
            if (location.toLowerCase().contains(text)) {
                filtered.add(location);
            }
            if (filtered.size() >= 10)
                break; // 最多显示10个建议
        }

        if (filtered.isEmpty()) {
            locationSuggestionPopup.setVisible(false);
            return;
        }

        // 更新建议列表
        suggestionList.setListData(filtered.toArray(new String[0]));
        locationSuggestionPopup.show(field, 0, field.getHeight());

        // 调整大小
        locationSuggestionPopup.setPopupSize(field.getWidth(), Math.min(filtered.size() * 25, 150));
    }

    /**
     * 加载位置历史记录
     */
    private void loadLocationHistory() {
        locationHistory.clear();

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DatabaseUtil.getConnection();
            String sql = "SELECT DISTINCT start_location FROM travel_records " +
                    "UNION SELECT DISTINCT end_location FROM travel_records";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                String location = rs.getString(1);
                if (location != null && !location.isEmpty()) {
                    locationHistory.add(location);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseUtil.closeConnection(conn, pstmt, rs);
        }
    }

    /**
     * 更新积分和碳减排预览
     */
    private void updatePointsAndCarbonPreview() {
        String distanceStr = distanceField.getText().trim();
        String travelType = (String) travelTypeComboBox.getSelectedItem();

        if (distanceStr.isEmpty()) {
            pointsPreviewLabel.setText("预计积分: 0");
            carbonPreviewLabel.setText("预计碳减排: 0.00 kg");
            return;
        }

        try {
            double distance = Double.parseDouble(distanceStr);
            if (distance <= 0) {
                pointsPreviewLabel.setText("预计积分: 0");
                carbonPreviewLabel.setText("预计碳减排: 0.00 kg");
                return;
            }

            // 计算积分和碳减排
            int points = calculatePoints(travelType, distance);
            double carbonReduction = calculateCarbonReduction(travelType, distance);

            pointsPreviewLabel.setText("预计积分: " + points);
            carbonPreviewLabel.setText("预计碳减排: " + String.format("%.2f", carbonReduction) + " kg");

        } catch (NumberFormatException e) {
            pointsPreviewLabel.setText("预计积分: 0");
            carbonPreviewLabel.setText("预计碳减排: 0.00 kg");
        }
    }

    /**
     * 计算积分
     */
    private int calculatePoints(String travelType, double distance) {
        int points = 0;

        switch (travelType) {
            case "公交":
                points = (int) (distance * 2);
                break;
            case "地铁":
                points = (int) (distance * 1.5);
                break;
            case "共享单车":
                points = (int) (distance * 3);
                break;
            case "自行车":
                points = (int) (distance * 4);
                break;
            case "步行":
                points = (int) (distance * 5);
                break;
        }

        return Math.max(points, 1); // 至少1积分
    }

    /**
     * 计算碳减排量
     */
    private double calculateCarbonReduction(String travelType, double distance) {
        double carbonReduction = 0;

        switch (travelType) {
            case "公交":
                carbonReduction = distance * 0.1; // 每公里减少0.1kg碳排放
                break;
            case "地铁":
                carbonReduction = distance * 0.08; // 每公里减少0.08kg碳排放
                break;
            case "共享单车":
                carbonReduction = distance * 0.22; // 每公里减少0.22kg碳排放
                break;
            case "自行车":
                carbonReduction = distance * 0.25; // 每公里减少0.25kg碳排放
                break;
            case "步行":
                carbonReduction = distance * 0.27; // 每公里减少0.27kg碳排放
                break;
        }

        return carbonReduction;
    }

    /**
     * 加载用户的出行记录
     */
    public void loadTravelRecords() {
        // 清空表格
        tableModel.setRowCount(0);

        TravelRecordDAO recordDAO = new TravelRecordDAO();
        List<TravelRecord> records = recordDAO.getUserTravelRecords(currentUser.getId());

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        for (TravelRecord record : records) {
            tableModel.addRow(new Object[] {
                    dateFormat.format(record.getTravelDate()),
                    record.getTravelType(),
                    record.getStartLocation(),
                    record.getEndLocation(),
                    record.getDistance(),
                    (double) record.getEarnedPoints(),
                    record.getCarbonReduction()
            });
        }
    }
}
